package com.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.dto.SetMealDto;
import com.reggie.pojo.Category;
import com.reggie.pojo.Dish;
import com.reggie.pojo.Setmeal;
import com.reggie.pojo.SetmealDish;
import com.reggie.service.ICategoryService;
import com.reggie.service.IDishService;
import com.reggie.service.ISetMealDishService;
import com.reggie.service.ISetMealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetMealController {
    @Autowired
    private ISetMealService setMealService;
    @Autowired
    private ISetMealDishService setMealDishService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IDishService dishService;

    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page> page(Integer page, Integer pageSize, String name){
        Page<Setmeal> pageBean = new Page<>(page, pageSize);
        //要返回的带套餐名的Page
        Page<SetMealDto> setMealDtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(name != null,Setmeal::getName,name);
        //更新时间降序排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //没有套餐分类的套餐数据
        setMealService.page(pageBean,lqw);

        //拷贝pageBean的数据到setMealDtoPage
        BeanUtils.copyProperties(pageBean,setMealDtoPage,"records");
        List<Setmeal> records = pageBean.getRecords();
        //获取每个套餐的分类id，通过id获取分类名称，并在每个setMealDto中设置分类名称
        List<SetMealDto> list = records.stream().map((item) ->{
            SetMealDto setMealDto = new SetMealDto();
            //每个对象拷贝属性
            BeanUtils.copyProperties(item,setMealDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                setMealDto.setCategoryName(categoryName);
            }
            return setMealDto;
        }).collect(Collectors.toList());
        //list设置在Page中并返回
        setMealDtoPage.setRecords(list);
        log.info(pageBean.getRecords().toString());
        log.info("--------------------------------");
        log.info(setMealDtoPage.getRecords().toString());
        return R.success(setMealDtoPage);
    }


    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//清除所有缓存
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetMealDto setMealDto){
        log.info("套餐信息：{}",setMealDto);

        setMealService.saveWithDish(setMealDto);

        return R.success("新增套餐成功！");
    }

    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//清除所有缓存
    @ApiOperation(value = "套餐删除接口")
    public R<String> delete(@RequestParam List<Long> ids){
        log.info(ids.toString());

        setMealService.removeWithDish(ids);
        return R.success("删除套餐成功！");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)//清除所有缓存
    @ApiOperation(value = "套餐修改状态接口")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Setmeal> qw = new LambdaUpdateWrapper<>();
        qw.set(Setmeal::getStatus,status);// set status = ?
        qw.in(Setmeal::getId,ids);//  where id in (1,2,3)
        setMealService.update(qw);

        return R.success("操作成功");
    }

    @GetMapping("/{id}")//修改回显数据 套餐(setMeal)+套餐菜品(setmeal_dish)+套餐名(category)
    @ApiOperation(value = "套餐根据id查询接口")
    public R<SetMealDto> getById(@PathVariable Long id){
        //把setMeal的属性复制给一个setMealDto
        SetMealDto setMealDto = new SetMealDto();
        Setmeal setmeal = setMealService.getById(id);
        BeanUtils.copyProperties(setmeal,setMealDto);

        //select * from setmeal_dish where setmeal_id = (setmeal表)id;
        LambdaQueryWrapper<SetmealDish> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setMealDishService.list(slqw);
        //套餐对应的餐品设置给setMealDto
        setMealDto.setSetmealDishes(setmealDishes);

        //select name from category where id = (setmeal表)category_id;
        LambdaQueryWrapper<Category> clqw = new LambdaQueryWrapper<>();
        clqw.eq(Category::getId,setmeal.getCategoryId());
        Category category = categoryService.getOne(clqw);
        //套餐对应的分类名设置给setMealDto
        setMealDto.setCategoryName(category.getName());

        return R.success(setMealDto);
    }

    @PutMapping//修改套餐 套餐(setMeal)+套餐菜品(setmeal_dish)+套餐名(category)
    @CacheEvict(value = "setmealCache",allEntries = true)//清除所有缓存
    @ApiOperation(value = "套餐修改接口")
    public R<String> update(@RequestBody SetMealDto setMealDto){
        //修改套餐数据 sluw name,price,description,image
        //update setMeal set name,price,description,image values
        //setMealDto.name,setMealDto.price,setMealDto.description,setMealDto.values
        //where id = setMealDto.id
        LambdaUpdateWrapper<Setmeal> sluw = new LambdaUpdateWrapper<>();
        sluw.set(Setmeal::getName,setMealDto.getName());
        sluw.set(Setmeal::getPrice,setMealDto.getPrice());
        sluw.set(Setmeal::getDescription,setMealDto.getDescription());
        sluw.set(Setmeal::getImage,setMealDto.getImage());
        sluw.eq(Setmeal::getId,setMealDto.getId());

        //修改套餐餐品数据 sdlqw
        //delete from setmeal_dish where setmeal_id = setMealDto.id
        //List<Dish> setmealdishes 遍历集合 dish设置对应套餐的id
        //insert into setmeal_dish 每个dish
        LambdaQueryWrapper<SetmealDish> sdlqw = new LambdaQueryWrapper<>();
        sdlqw.eq(SetmealDish::getSetmealId,setMealDto.getId());
        //删除修改前套餐关联的菜品(-----------------------没删掉---删掉了-逻辑删除)
        setMealDishService.remove(sdlqw);
        List<SetmealDish> dishes = setMealDto.getSetmealDishes();
        for (SetmealDish dish : dishes) {
            //添加传过来的套餐关联的菜品
            dish.setSetmealId(setMealDto.getId());
            setMealDishService.save(dish);
        }

        //修改套餐名称数据
        //select id from category where name = (setMealDto.categoryName)
        //update setMeal set category_id value (id);
//        LambdaQueryWrapper<Category> clqw = new LambdaQueryWrapper<>();
//        clqw.eq(Category::getName,setMealDto.getCategoryName());
//        Category category = categoryService.getOne(clqw);
//        log.info("修改后的套餐名："+setMealDto.getCategoryName());
//        log.info("修改后的id:"+category.getId().toString());
        //---------------------套餐名称没改 传过来的套餐名称还是原来的名称，id还是原来的id

        //=============前台传过来的套餐名称是修改前的套餐名称
        //=============传过来的CategoryId才是修改后的套餐id---直接修改id即可
        sluw.set(Setmeal::getCategoryId,setMealDto.getCategoryId());
        setMealService.update(sluw);
        return R.success("修改套餐成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    @ApiOperation(value = "套餐条件查询接口")
    public R<List<Setmeal>> getSetMeals(Long categoryId,Integer status){
        //客户端查询套餐列表 setmeal表中的 category_id 和 status
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getCategoryId,categoryId).eq(Setmeal::getStatus,status);
        List<Setmeal> list = setMealService.list(lqw);
        return R.success(list);
    }

}
